using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.DeviceDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.BasicManagement.DeviceDictionaryHandler
{
    /// <summary>
    /// 设备查询处理器
    /// </summary>
    public class QueryEquipmentHandler : IRequestHandler<QueryEquipmentCommand, ApiResult<ApiPageIng<Equipment>>>
    {
        private readonly IBaseRepository<Equipment> _equipmentRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="equipmentRepository">设备仓储</param>
        public QueryEquipmentHandler(IBaseRepository<Equipment> equipmentRepository)
        {
            _equipmentRepository = equipmentRepository;
        }

        /// <summary>
        /// 处理查询请求
        /// </summary>
        public Task<ApiResult<ApiPageIng<Equipment>>> Handle(QueryEquipmentCommand request, CancellationToken cancellationToken)
        {
            var query = _equipmentRepository.GetAll().Where(e => !e.IsDeleted);

            // 按设备类型过滤
            if (request.QueryDto.EquipmentType.HasValue)
            {
                query = query.Where(e => e.EquipmentType == request.QueryDto.EquipmentType.Value);
            }

            // 按状态过滤
            if (request.QueryDto.Status.HasValue)
            {
                query = query.Where(e => e.Status == request.QueryDto.Status.Value);
            }

            // 分页查询
            var totalCount = query.Count();
            var items = query
                .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                .Take(request.QueryDto.PageSize)
                .ToList();

            return Task.FromResult(new ApiResult<ApiPageIng<Equipment>>
            {
                Code = ApiEnums.Success,
                Msg = "设备列表查询成功",
                Data = new ApiPageIng<Equipment>
                {
                    TotalCount = totalCount,
                    PageData = items,
                }
            });
        }
    }
}